/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.fsm
{
	import com.qb9.flashlib.lang.AbstractMethodError;
	import com.qb9.flashlib.events.QEvent;
	import flash.events.Event;
	import flash.events.IEventDispatcher;

	internal class BaseTransition implements Transition
	{
		protected var state:State;
		
		protected var _defaultTransition:String;
		protected var _action:Function;

		public function BaseTransition(state:State)
		{
			this.state = state;
		}

		public function action(handler:Function):Transition
		{
			_action = handler;
			return this;
		}
		
		public function goto(name:String):Transition
		{
			_defaultTransition = name;
			return this;
		}
		
		public function onEvent(type:String, dispatcher:IEventDispatcher = null):Transition
		{
			return state.onEvent(type, dispatcher);
		}

		public function after(milliseconds:uint):Transition
		{
			return state.after(milliseconds);
		}
		
		public function get id():String
		{
			throw new AbstractMethodError();
		}

		protected function get eventSource():IEventDispatcher
		{
			return this.state;
		}

		protected function get eventType():String
		{
			throw new AbstractMethodError();
		}

		public function startListening():void
		{
			eventSource.addEventListener(eventType, handleEvent);
		}

		public function stopListening():void
		{
			eventSource.removeEventListener(eventType, handleEvent);
		}

		protected function handleEvent(event:Event):void
		{
			var next:String;
			if (_action != null)
				next = _action(event);
			next ||= _defaultTransition;
			if (event.isDefaultPrevented() || next == null)
				return;
			var data:* = event is QEvent ? ((event as QEvent).data) : null;
			state.requestTransition(next, data);
		}
	}
}
